package com.ys.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ys.common.utils.HttpUtils;
import com.ys.common.utils.R;
import com.ys.gulimall.auth.feign.MemberFeignService;
import com.ys.common.vo.MemberResponseVo;
import com.ys.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * @Description:
 * @author： yeswater
 * @create： 2024/5/16
 */

@Slf4j
@Controller
public class OAuth2Controller {
	
	@Value("${gitee.client-id}")
	private String CLIENT_ID;
	
	@Value("${gitee.client-secret}")
	private String CLIENT_SECRET;
	
	@Value("${gitee.grant-type}")
	private String GRANT_TYPE;
	
	@Value("${gitee.redirect-uri}")
	private String REDIRECT_URI;
	
	@Value("${gitee.host}")
	private String HOST;
	
	@Value("${gitee.path}")
	private String PATH;
	
	@Resource
	private MemberFeignService memberFeignService;
	
	@RequestMapping("/oauth2.0/weibo/success")
	public String authorize(String code, RedirectAttributes attributes, HttpSession session) throws Exception {
		// 使用 code 换取 token，换取成功则继续，否则重定向到登录页
		HashMap<String, String> query = new HashMap<>();
		query.put("client_id", CLIENT_ID);
		query.put("client_secret", CLIENT_SECRET);
		query.put("grant_type", GRANT_TYPE);
		query.put("redirect_uri", REDIRECT_URI);
		query.put("code", code);
		HashMap<String, String> header = new HashMap<>();
		HashMap<String, String> body = new HashMap<>();
		HttpResponse response = HttpUtils.doPost(HOST, PATH, "post", header, query, body);
		HashMap<String, String> errors = new HashMap<>();
		if (response.getStatusLine().getStatusCode() == 200) {
			// 2. 调用member远程接口进行oauth登录，登录成功则转发至首页并携带返回用户信息，否则转发至登录页
			String json = EntityUtils.toString(response.getEntity());
			SocialUser socialUser = JSON.parseObject(json, new TypeReference<SocialUser>() {
			});
			R login = memberFeignService.oauth2Login(socialUser);
			log.info("远程调用结果="+JSON.toJSONString(login));
			// 2.1 远程调用成功，返回首页并携带用户信息
			if (login.getCode() == 0) {
				MemberResponseVo loginUser = login.getData("data", new TypeReference<MemberResponseVo>() {});
				session.setAttribute("loginUser", loginUser);
				log.info("登陆成功：用户信息" + JSON.toJSONString(loginUser));
				return "redirect:http://gulimall.com";
			}else {
				// 2.2 否则返回登录页
				errors.put("msg", "登录失败，请重试");
				attributes.addFlashAttribute("errors", errors);
				return "redirect:http://auth.gulimall.com/login.html";
			}
		}else {
			errors.put("msg", "获得第三方授权失败，请重试");
			attributes.addFlashAttribute("errors", errors);
			return "redirect:http://auth.gulimall.com/login.html";
		}
	}
	
}
